package org.Lin.client;

import javax.swing.*;
import java.awt.*;

import org.Lin.util.AESUtil;
import org.Lin.util.HashUtil;
import org.json.JSONObject;

public class LoginClient {
    private JFrame frame;
    private JTextField userIDField;
    private JPasswordField passwordField;

    public void show() {
        frame = new JFrame("用户登录");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(4, 2));

        frame.add(new JLabel("用户ID:"));
        userIDField = new JTextField();
        frame.add(userIDField);

        frame.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        frame.add(passwordField);

        JButton loginButton = new JButton("登录");
        JButton registerButton = new JButton("注册");

        loginButton.addActionListener(e -> {
            String userID = userIDField.getText();
            String password = new String(passwordField.getPassword());

            JSONObject request = new JSONObject();
            request.put("type", "login");
            request.put("userID", userID);
            request.put("password", HashUtil.hashPassword(password)); // 密码哈希处理

            try {
                String encrypted = AESUtil.encrypt(request.toString());
                NetworkClient.send(encrypted);
                JOptionPane.showMessageDialog(frame, "登录请求已发送");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(frame, "发送失败: " + ex.getMessage());
            }
        });

        registerButton.addActionListener(e -> {
            new RegisterClient().show();
            frame.dispose();
        });

        frame.add(loginButton);
        frame.add(registerButton);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new LoginClient().show());
    }
}
